#include <stdio.h>
#include <string.h>

void reverse(char *s, int head, int tail) {
	for (int i = head, j = tail; i < j; i++, j--) {
		int temp = s[i];
		s[i] = s[j];
		s[j] = temp;
	}
}

void reduceExtraSpace(char *s) {
	int head = 0, tail = strlen(s) - 1;
	while (s[head] == ' ')
		head++;
	while (s[tail] == ' ')
		tail--;

	int slow = 0;
	for (int fast = head; fast <= tail; fast++) {
		if (s[fast] == ' ' && s[fast + 1] == ' ')
			continue;
		s[slow++] = s[fast];
	}
	s[slow] = '\0';
}

char *reverseWords(char *s) {
	reduceExtraSpace(s);
	reverse(s, 0, (int)strlen(s) - 1);

	int head = 0;
	for (int i = head; i <= (int)strlen(s); i++) {
		if (s[i] == ' ' || s[i] == '\0') {
			reverse(s, head, i - 1);
			head = i + 1;
		}
	}
	return s;
}

void main() {
	char s[] = "I am love the home";

	reverseWords(s);
	for (int i = 0; i < (int)strlen(s); i++) {
		printf("%c", s[i]);
	}
}